package Servleet;

import LoginManager.Login;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "text/javascript;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + " " + password);
        //COOKIE
        Cookie cookieName=new Cookie("username", username);
        Cookie cookiePassword=new Cookie("password", password);
        cookieName.setMaxAge(60*60*24);
        cookiePassword.setMaxAge(60*60*24);
        response.addCookie(cookieName);
        response.addCookie(cookiePassword);
        JSONObject obj = new JSONObject();

        Login login = new Login(username,password);
        String warn = login.loginStimulate();
        System.out.println("........." + warn);
        if(warn != null){
            obj.put("message",warn);;
            if(login.getStatus()){
                obj.put("message","正在转入登录界面");
                obj.put("susscessUrl",warn);
                System.out.println("登录成功");
            }
        }

        String result = JSON.toJSONString(obj);
        System.out.println(result);
        out.print(result);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "text/javascript;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        JSONObject obj = new JSONObject();

        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("username")){
                obj.put("username", cookie.getValue());
            }
            if(cookie.getName().equals("password")){
                obj.put("password", cookie.getValue());
            }
        }

        String result = JSON.toJSONString(obj);
        System.out.println(result);
        out.print(result);
    }

}
